<template>
  <div class="zhanghuLogin">
    <!-- 手机号 密码 -->
    <el-form
      label-position="left"
      label-width="80px"
      :model="loginForm"
      ref="loginFormRef"
      :rules="loginFormRules"
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="loginForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" type="password"></el-input>
      </el-form-item>
    </el-form>
    <!-- 验证码 -->
    <el-form
      :inline="true"
      :model="captchaForm"
      label-width="80px"
      label-position="left"
      ref="captchaFormRef"
      :rules="captchaFormRules"
    >
      <el-form-item label="验证码" prop="captcha">
        <el-input
          v-model="captchaForm.captcha"
          placeholder="请输入验证码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="disabledFlag" @click="sendCaptcha">{{
          captchaFormText
        }}</el-button>
      </el-form-item>
    </el-form>
    <br />
    <!-- 忘记密码 和 立即注册 -->
    <el-row type="flex" justify="end">
      <el-col :span="7">
        <el-link @click="toRegisterPage">立即注册</el-link>
        <el-link>忘记密码</el-link>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" class="captcha captcha2" @click="userLogin"
          >登录</el-button
        >
      </el-col>
    </el-row>
    <!-- <h2>vuex{{ userStoreCookie }}</h2> -->
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import {
  getCaptcha,
  verifyCaptcha,
  phoneLogin,
} from "../../../api/loginApi.js";
import {
  setLocalStorgeItem,
  getLocalStorgeItem,
  deleteLocalStorgeItem,
  deleteLocalStorgeAll,
} from "../../../utils/storage";
export default {
  name: "zhanghuLogin",
  components: {},
  data() {
    var validatePhone = (rule, value, callback) => {
      // ^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$  验证手机号
      // 真 / 假
      // let regPhone =
      //   /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
      let regPhone =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!regPhone.test(value)) {
        callback(new Error("请输入正确的手机号格式"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        phone: "",
        password: "",
      },
      loginFormRules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "请输入正确的手机号位数",
            trigger: "blur",
          },
          { validator: validatePhone, trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      captchaForm: {
        captcha: "",
      },
      captchaFormRules: {
        captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            min: 4,
            max: 4,
            message: "请输入正确的验证码位数",
            trigger: "blur",
          },
        ],
      },
      captchaFormText: "获取验证码",
      disabledFlag: false,
    };
  },
  created() {
    // setLocalStorgeItem("age", 10);
    // setLocalStorgeItem("ddg", 10);
    // console.log(getLocalStorgeItem("age"));
    // deleteLocalStorgeAll();
  },
  methods: {
    ...mapMutations("userStore", [
      "changeProfile",
      "changeCookie",
      "changeToken",
    ]),
    ...mapActions("userStore", ["getUserDetailActions"]),
    async sendCaptcha() {
      // 前提保证 手机号已经输入了，并且格式正确
      // let validatePhonePromise;
      try {
        let s = 60;
        let timer;
        let validatePhonePromise = await new Promise((resole, reject) => {
          this.$refs.loginFormRef.validateField("phone", (phoneError) => {
            // 手机号 验证出错的情况
            // console.log("验证返回的结果", phoneError);
            if (phoneError.length != 0) {
              this.$message({
                message: phoneError,
                type: "error",
              });
              reject(phoneError);
            } else {
              // 如果验证的结果要是真的，那就会 返回 空
              resole(phoneError);
            }
          });
        });
        // 验证手机号成功 ，进入 发送验证码环节
        let getCaptchaResult = await getCaptcha(this.loginForm.phone);
        if (getCaptchaResult.code === 200) {
          // 验证码发送成功~
          this.$message({
            message: `向${this.loginForm.phone} 账户 发送验证码成功`,
            type: "success",
          });
          this.disabledFlag = true;
          timer = setInterval(() => {
            if (s == 0) {
              clearInterval(timer);
              this.captchaFormText = "获取验证码";
              this.disabledFlag = false;
              return;
            }
            this.captchaFormText = `${s}s后重试`;
            s--;
          }, 1000);
        } else {
          // 验证码 发送失败
          this.$message({
            message: getCaptchaResult.message,
            type: "error",
          });

          throw new Error(getCaptchaResult.message);
        }
      } catch (error) {
        console.log(error, "catch捕获错误");
      }
      // console.log("await 返回的结果", validatePhonePromise);

      // console.log("点击了");
      // this.disabledFlag = true;
      // let s = 60;
      // let timer = setInterval(() => {
      //   if (s == 0) {
      //     clearInterval(timer);
      //     this.captchaFormText = "获取验证码";
      //     this.disabledFlag = false;
      //     return;
      //   }
      //   this.captchaFormText = `${s}s后重试`;
      //   s--;
      // }, 1000);

      // 发送验证码
    },
    // 用户登录
    async userLogin() {
      // 要保证 验证码表单和 账号密码表单 都验证成功，才可以发送网络请求进行登录
      try {
        // 验证 账号密码表单
        let loginFormValidate = await new Promise((resolve, reject) => {
          this.$refs.loginFormRef.validate((flag) => {
            if (flag) {
              // 真的， 验证成功
              resolve(true);
            } else {
              this.$message({
                message: "请根据错误信息，完善账户信息",
                type: "error",
              });
              reject(false);
            }
          });
        });
        // 验证 验证码表单
        let captchaFormValidate = await new Promise((resolve, reject) => {
          this.$refs.captchaFormRef.validate((flag) => {
            if (flag) {
              // 真的， 验证成功
              resolve(true);
            } else {
              this.$message({
                message: "请根据错误信息，完善验证码",
                type: "error",
              });
              reject(false);
            }
          });
        });
        if (loginFormValidate && captchaFormValidate) {
          //  验证验证码 的接口， 如果错误，服务器也会返回500 系列的错误，所以也要用到 catch 捕获
          let verifyCaptchaResult = await verifyCaptcha({
            phone: this.loginForm.phone,
            captcha: this.captchaForm.captcha,
          });

          //  手机号，登录，如果 密码错误啥的， 服务器会返回 500系列的错误，所以 要用到 catch 捕获
          let verifyLoginResult = await phoneLogin(this.loginForm);
          console.log(verifyLoginResult);

          if (
            verifyCaptchaResult.code === 200 &&
            verifyLoginResult.code === 200
          ) {
            setLocalStorgeItem("profile", verifyLoginResult.profile);
            setLocalStorgeItem("cookie", verifyLoginResult.cookie);
            setLocalStorgeItem("token", verifyLoginResult.token);

            /* 配合vuex */
            this.changeProfile(verifyLoginResult.profile);
            this.changeCookie(verifyLoginResult.cookie);
            this.changeToken(verifyLoginResult.token);
            await this.getUserDetailActions();

            console.log(this.$route);
            // 重置表单 并 跳转到 原来的页面
            this.$refs.loginFormRef.resetFields();
            this.$refs.captchaFormRef.resetFields();
            this.$router.push(this.$route.query.path);
          }
        }
        // let arrResult = new Promise.all()
      } catch (error) {
        this.$message({
          message: error.response.data.message,
          type: "error",
        });
      }
    },

    // 为了方便，先取消  验证码的 验证
    // async userLogin() {
    //   // 要保证 验证码表单和 账号密码表单 都验证成功，才可以发送网络请求进行登录
    //   try {
    //     // 验证 账号密码表单
    //     let loginFormValidate = await new Promise((resolve, reject) => {
    //       this.$refs.loginFormRef.validate((flag) => {
    //         if (flag) {
    //           // 真的， 验证成功
    //           resolve(true);
    //         } else {
    //           this.$message({
    //             message: "请根据错误信息，完善账户信息",
    //             type: "error",
    //           });
    //           reject(false);
    //         }
    //       });
    //     });
    //     // // 验证 验证码表单
    //     // let captchaFormValidate = await new Promise((resolve, reject) => {
    //     //   this.$refs.captchaFormRef.validate((flag) => {
    //     //     if (flag) {
    //     //       // 真的， 验证成功
    //     //       resolve(true);
    //     //     } else {
    //     //       this.$message({
    //     //         message: "请根据错误信息，完善验证码",
    //     //         type: "error",
    //     //       });
    //     //       reject(false);
    //     //     }
    //     //   });
    //     // });
    //     if (loginFormValidate) {
    //       //  验证验证码 的接口， 如果错误，服务器也会返回500 系列的错误，所以也要用到 catch 捕获
    //       // let verifyCaptchaResult = await verifyCaptcha({
    //       //   phone: this.loginForm.phone,
    //       //   captcha: this.captchaForm.captcha,
    //       // });

    //       //  手机号，登录，如果 密码错误啥的， 服务器会返回 500系列的错误，所以 要用到 catch 捕获
    //       let verifyLoginResult = await phoneLogin(this.loginForm);
    //       console.log(verifyLoginResult);

    //       // if (
    //       //   verifyCaptchaResult.code === 200 &&
    //       //   verifyLoginResult.code === 200
    //       // ) {
    //       setLocalStorgeItem("profile", verifyLoginResult.profile);
    //       setLocalStorgeItem("cookie", verifyLoginResult.cookie);
    //       setLocalStorgeItem("token", verifyLoginResult.token);

    //       /* 配合vuex */
    //       this.changeProfile(verifyLoginResult.profile);
    //       this.changeCookie(verifyLoginResult.cookie);
    //       this.changeToken(verifyLoginResult.token);
    //       await this.getUserDetailActions();

    //       console.log(this.$route);
    //       // 重置表单 并 跳转到 原来的页面
    //       this.$refs.loginFormRef.resetFields();
    //       this.$refs.captchaFormRef.resetFields();
    //       this.$router.push(this.$route.query.path);
    //       // }
    //     }
    //     // let arrResult = new Promise.all()
    //   } catch (error) {
    //     this.$message({
    //       message: error.response.data.message,
    //       type: "error",
    //     });
    //   }
    // },

    // 前往 立即注册页面
    toRegisterPage() {
      console.log(this.$route.query.path);
      this.$router.push({
        path: "/register",
        query: {
          path: encodeURI(this.$route.query.path),
        },
      });
    },
  },
  computed: {
    ...mapState({
      userStoreProfile: (state) => state.userStore.profile,
      userStoreCookie: (state) => state.userStore.cookie,
      userStoreToken: (state) => state.userStore.token,
    }),
  },
};
</script>

<style lang="less" scoped>
.zhanghuLogin {
  padding: 20px 40px;
  padding-top: 100px;
  .captcha {
    // /deep/ .el-button {
    //   background-color: @globalColor !important;
    // }
    background-color: @globalColor !important;
    border: none;
  }
  .captcha2 {
    // height: 55px;
    width: 100px;
  }
  /deep/ .el-link {
    margin-left: 8px;
    &:hover {
      color: @globalColor;
    }
  }
}
</style>
